package cn.ecpay.unionpay.settle.dao;

import cn.ecpay.unionpay.settle.entity.db.TPvFundSettleSingle;
import cn.ecpay.unionpay.settle.entity.db.TPvRealTimeBalanceQuery;
import org.rex.DB;
import org.rex.db.Ps;
import org.rex.db.exception.DBException;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 单笔查询
 * Created by zhaoyanzeng on 2018/12/11.
 */
@Repository
public class RealTimeBalanceQueryDao {

    /**
     * 保存实时查询
     * @param realTimeBalanceQuery
     */
    public void insert(TPvRealTimeBalanceQuery realTimeBalanceQuery) throws DBException {
        String sql = "INSERT INTO T_PV_REAL_TIME_BALANCE_QUERY" +
                "(ID,TXN_NO,TXN_TYPE,ACQ_INS_CODE,TXN_DATE,SND_TIME,ACCT_NAME,ACCT_NO,CURRENCY_CODE,RESP_CODE,RESP_MSG,RESP_VALIDATE," +
                "CREATE_TIME,ACCT_BAL,AVLB_BAL,REMARK)" +
                " VALUES " +
                "(#{id},#{txnNo},#{txnType},#{acqInsCode},#{txnDate},#{sndTime},#{acctName},#{acctNo},#{currencyCode},#{respCode}," +
                "#{respMsg},#{respValidate},#{createTime},#{acctBal},#{avlbBal},#{remark})" ;
        DB.update(sql, realTimeBalanceQuery);
    }

    /**
     * 更新通知结果
     * @param realTimeBalanceQuery
     */
    public void updateNotify(TPvRealTimeBalanceQuery realTimeBalanceQuery) throws DBException {
        String sql = "UPDATE T_PV_REAL_TIME_BALANCE_QUERY SET NOTIFY_RESP_CODE=#{notifyRespCode},NOTIFY_RESP_MSG=#{notifyRespMsg}," +
                "IS_NOTIFY=#{isNotify},NOTIFY_TIME=#{notifyTime},NOTIFY_VALIDATE=#{notifyValidate} WHERE TXN_NO=#{txnNo}";
        DB.update(sql, realTimeBalanceQuery);
    }

    /**
     *  根据ID获取交易信息
     * @param id
     * @return
     * @throws DBException
     */
    public TPvRealTimeBalanceQuery findById(String id) throws DBException {
        String sql = "SELECT * FROM T_PV_REAL_TIME_BALANCE_QUERY WHERE ID=?";
        return DB.get(sql,new Object[]{id},TPvRealTimeBalanceQuery.class);
    }

    /**
     * 根据流水号获取交易信息
     * @param txnNo 流水号
     * @return
     * @throws DBException
     */
    public TPvRealTimeBalanceQuery findByTxnNo(String txnNo) throws DBException {
        String sql = "SELECT * FROM T_PV_REAL_TIME_BALANCE_QUERY WHERE TXN_NO=?";
        return DB.get(sql,new Object[]{txnNo},TPvRealTimeBalanceQuery.class);
    }

    /**
     * 当天交易流水号不能重复
     * @param txnNo
     * @param txnDate
     * @return
     * @throws DBException
     */
    public boolean isExistTxn(String txnNo, String txnDate) throws DBException {
        Ps ps = new Ps();
        String sql = "SELECT * FROM T_PV_REAL_TIME_BALANCE_QUERY WHERE TXN_NO=? and TXN_DATE =?";
        ps.add(txnNo);
        ps.add(txnDate);
        List<TPvFundSettleSingle> list = DB.getList(sql,ps,TPvFundSettleSingle.class);
        if(list!= null && list.size()>0){
            return true;
        }
        return false;
    }
}
